package com.kuizii.base.common.idgenerator;


import com.kuizii.base.common.utils.MACUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.text.SimpleDateFormat;
import java.time.Duration;

/**
 *
 * 不推荐使用 可能导致主从频繁同步删除ID
 * @Author: nuanyang
 * @Date: 2019/8/16 0016 11:07
 */
@ConditionalOnClass(value = RedisTemplate.class)
@ConditionalOnBean(value = RedisTemplate.class)
public class RedisIdGenerator extends NodeDistribute implements IdGenerator<String> {

    public void setSimpleDateFormat(SimpleDateFormat simpleDateFormat) {
        this.simpleDateFormat = simpleDateFormat;
    }

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    @Autowired
    RedisTemplate redisTemplate;

    String nodeId;

    long delta = 1;

    @Override
    public String newId() {

        String now = simpleDateFormat.format(System.currentTimeMillis());
        Long no = redisTemplate.opsForValue().increment("redis-id-generator" + now, delta);
        redisTemplate.expire("redis-id-generator"+ now, Duration.ofSeconds(10));

        return now + StringUtils.leftPad(String.valueOf(nodeId), 3, '0') + StringUtils.leftPad(no.toString(), 6, '0');
    }


    @Override
    public void afterPropertiesSet() {
        //先判断是否配置环境变量，如没配就根据IP自动添加节点
        if (StringUtils.isNotBlank(System.getenv().getOrDefault("NODE_ID", ""))) {
            nodeId = System.getenv().get("NODE_ID");
        } else {
            String ip = MACUtil.getIp();
            int nodeSize = redisTemplate.opsForHash().keys("id-generater-node").size();
            if (redisTemplate.opsForHash().get("id-generater-node", ip) == null) {
                redisTemplate.opsForHash().put("id-generater-node", ip, String.valueOf(nodeSize + 1));
            }
            nodeId = redisTemplate.opsForHash().get("id-generater-node", ip).toString();
        }

        System.out.println("当前节点id为：" + nodeId);
    }
}
